package Model;

import java.sql.*;
import java.util.ArrayList;
import com.sun.rowset.CachedRowSetImpl;

import Database.*;
import Helper.*;

public class UserM extends Model {
    ArrayList<User> cache = null;

    public User login(String name, String password){
        UserM userM = new UserM();
        ArrayList<User> temp = userM.find(name);

        User result = null;

        if( temp.size() == 1 ){
            User u = temp.get(0);

            if( u.name.equals(name) && u.getPassword().equals(Helper.md5(password)) ){
                u.setStatus(name, Helper.md5(password));

                result = u;
            }else{
                System.err.println("用户名或密码错误！");
            }
        }else{
            System.err.println("用户名不存在！");
        }

        return result;
    }

    public boolean signup(String name, String password){
        User u = new User(name,Helper.md5(password));

        UserM userM = new UserM();

        return userM.add(u);
    }

    public ArrayList<Order> getOrders(int id){
        // list buy record
        ArrayList<Order> orders = new ArrayList<>();

        UserDB db = new UserDB();
        CachedRowSetImpl res = db.selectOrders(id);

        try{
            while( res.next() ){

                int oid = res.getInt(1);
                int pid = res.getInt(2);
                String name = res.getString(3);
                float pPrice = res.getFloat(4);
                int amount = res.getInt(5);
                float oPrice = res.getFloat(6);
                int status = res.getInt(7);

                Order o = new Order();
                o.id = oid;
                o.productId = pid;
                o.name = name;
                o.productPrice = pPrice;
                o.price = oPrice;
                o.amount = amount;
                o.status = status;

                orders.add(o);
            }
        }catch (SQLException exception){
            System.err.println("数据库出错！");
            if( Helper.isDev ){
                exception.printStackTrace();
            }
        }

        return orders;
    }

    public boolean buy(int uid, int pid, int amount, float price){
        UserDB db = new UserDB();

        return db.buy(uid, pid, amount, price);
    }

    private boolean add(User u){
        UserDB db = new UserDB();

        return db.insert(u);
    }


    private ArrayList<User> find(String name){
        UserDB db = new UserDB();

        CachedRowSetImpl res = db.match(name);

        return createuserArr(res);
    }

    protected void init(String tableName){
        // override
        UserDB db = new UserDB();

        CachedRowSetImpl res = db.get(tableName);

        cache = createuserArr(res);
    }

    private ArrayList<User> createuserArr(CachedRowSetImpl res){
        // override

        ArrayList<User> result = new ArrayList<>();

        try {
            while (res.next()) {
                User u = new User(res.getString(3),res.getString(4));
                u.id = res.getInt(1);

                result.add(u);
            }
        } catch (SQLException exception) {
            System.err.println("数据库出错！");
            if( Helper.isDev ){
                exception.printStackTrace();
            }
        }

        return result;
    }
}

class UserDB extends DB{
    boolean insert(User u){
        int result = -1;

        try{
            connect();

            String sql = "INSERT INTO tb_account(name,password,auth) VALUES(?,?,0)";
            PreparedStatement statement = dbConnection.prepareStatement(sql);
            statement.setString(1,u.name);
            statement.setString(2,u.getPassword());

            result = statement.executeUpdate();
        }catch(SQLException exception){
            System.err.println("用户已存在！或其他数据库错误");
            if( Helper.isDev ){
                exception.printStackTrace();
            }
        }finally {
            close();
        }

        if( result >= 0 ){
            return true;
        }else{
            return false;
        }
    }

    CachedRowSetImpl match(String name){
        CachedRowSetImpl cachedRowSet = null;

        try{
            connect();

            String sql = "SELECT * FROM tb_account WHERE name=? AND auth=0";
            PreparedStatement statement = dbConnection.prepareStatement(sql);
            statement.setString(1, name);

            ResultSet res = statement.executeQuery();

            cachedRowSet = new CachedRowSetImpl();
            cachedRowSet.populate(res);
        }catch(SQLException exception){
            System.err.println("数据库出错！");
            if( Helper.isDev ){
                exception.printStackTrace();
            }
        }finally {
            close();
        }

        return cachedRowSet;
    }

    CachedRowSetImpl selectOrders(int uid){
        CachedRowSetImpl cachedRowSet = null;

        try{
            connect();

            String sql = "SELECT o.id,p.id,p.name,p.price,o.amount,o.price,o.status FROM tb_order o,tb_product p WHERE o.customer_id=? AND p.id=o.product_id";
            PreparedStatement statement = dbConnection.prepareStatement(sql);
            statement.setInt(1, uid);

            ResultSet res = statement.executeQuery();

            cachedRowSet = new CachedRowSetImpl();
            cachedRowSet.populate(res);
        }catch(SQLException exception){
            System.err.println("数据库出错！");
            if( Helper.isDev ){
                exception.printStackTrace();
            }
        }finally {
            close();
        }

        return cachedRowSet;
    }

    private boolean createOrder(int uid, int pid, int amount,float price){
        int result = -1;

        try{
            connect();

            String sql = "INSERT INTO tb_order(customer_id,product_id,amount,price,cdate,status) VALUES(?,?,?,?,?,?)";
            PreparedStatement statement = dbConnection.prepareStatement(sql);
            statement.setInt(1,uid);
            statement.setInt(2,pid);
            statement.setInt(3,amount);
            statement.setFloat(4, price);
            statement.setTimestamp(5, Timestamp.valueOf(new java.util.Date().toLocaleString()));
            statement.setInt(6, 0);

            result = statement.executeUpdate();
        }catch(SQLException exception){
            System.err.println("数据库出错！");
            if( Helper.isDev ){
                exception.printStackTrace();
            }
        }finally {
            close();
        }

        if( result >= 0 ){
            return true;
        }else{
            return false;
        }
    }

    private boolean reduceProductAmount(int pid, int amount){
        int result = -1;

        try{
            connect();

            String sql = "UPDATE tb_product SET amount=amount-? WHERE id=?";
            PreparedStatement statement = dbConnection.prepareStatement(sql);
            statement.setInt(1,amount);
            statement.setInt(2,pid);

            result = statement.executeUpdate();
        }catch(SQLException exception){
            System.err.println("数据库出错！");
            if( Helper.isDev ){
                exception.printStackTrace();
            }
        }finally {
            close();
        }

        if( result >= 0 ){
            return true;
        }else{
            return false;
        }
    }

    boolean buy(int uid, int pid, int amount, float price){
        ProductM productM = new ProductM();
        ArrayList<Product> p = productM.find(pid);
        int oldAmount = p.get(0).amount;

        if( oldAmount < amount ){
            System.err.println(p.get(0).name+"储量不足！");
            return false;
        }else{
            return createOrder(uid, pid, amount, price) &&
                    reduceProductAmount(pid, amount);
        }
    }
}
